<template>
  <d2-container>
    <el-row :gutter="20">
      <el-col :span="8">
        <!--  项目名称-->
        <el-select
          filterable
          v-model="projectId"
          placeholder="请选择项目名称"
          @change="handleSelectDatabase"
          class="generator-left-select"
        >
          <el-option
            v-for="item in projectList"
            :key="item.name"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>

        <!--  数据库表-->
        <el-col :span="12" v-show="projectId">
          <div>
            <el-input
              clearable
              size="small"
              placeholder="请搜索表"
              v-model="searchValue"
              @input="searchSurfaceList"
              class="generator-left-search"
            ></el-input>
            <div v-show="copySurfaceList.length > 0">
              <el-checkbox
                :indeterminate="isIndeterminate"
                v-model="checkAll"
                @change="handleCheckAllChange"
                class="generator-left-all-check"
                >全选
              </el-checkbox>
              <el-checkbox-group
                v-model="checkedSurface"
                @change="handleCheckedChange"
                class="generator-left-surface"
              >
                <el-checkbox
                  v-for="table in surfaceList"
                  :label="table"
                  :key="table"
                  >{{ table }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
            <div
              class="generator-left-surface"
              v-show="surfaceList.length === 0 && copySurfaceList.length === 0"
            >
              <el-empty
                :image-size="60"
                description="暂无表"
                style="padding-top: 20px"
              ></el-empty>
            </div>
          </div>
        </el-col>

        <!--  模板-->
        <el-col :span="12" v-show="projectId">
          <div>
            <el-input
              clearable
              size="small"
              placeholder="请搜索模板"
              v-model="searchValueTemplate"
              @input="searchTemplateList"
              class="generator-left-search"
            ></el-input>
            <div v-show="copyTemplateList.length > 0">
              <el-checkbox
                :indeterminate="isIndeterminateTemplate"
                v-model="checkAllTemplate"
                @change="handleCheckAllChangeTemplate"
                class="generator-left-all-check"
                >全选
              </el-checkbox>
              <el-checkbox-group
                v-model="checkedTemplate"
                @change="handleCheckedChangeTemplate"
                class="generator-left-surface"
              >
                <el-checkbox
                  v-for="item in templateList"
                  :label="item.id"
                  :key="item.id"
                  >{{ item.name }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
            <div
              class="generator-left-surface"
              v-show="
                templateList.length === 0 && copyTemplateList.length === 0
              "
            >
              <el-empty
                :image-size="60"
                description="暂无模板"
                style="padding-top: 20px"
              ></el-empty>
            </div>
          </div>
        </el-col>

        <el-empty
          :image-size="100"
          description="请选择项目"
          v-show="!projectId"
          style="padding-top: 70px"
        ></el-empty>
      </el-col>

      <!-- 配置 -->
      <el-col :span="16">
        <div class="generator-rigth-setting">
          <el-form
            :model="settingsForm"
            :rules="rules"
            ref="settingsForm"
            label-width="100px"
            class="demo-settingsForm"
          >
            <el-card class="box-card">
              <div slot="header" class="clearfix"><span>基本配置</span></div>
              <div>
                <el-form-item label="基础包名" prop="packageName">
                  <el-input
                    v-model="settingsForm.packageName"
                    placeholder="请输入基础包名"
                  ></el-input>
                </el-form-item>
              </div>
            </el-card>
            <el-card class="box-card">
              <div slot="header" class="clearfix"><span>高级配置</span></div>
              <div>
                <el-form-item label="作者" prop="author">
                  <el-input
                    v-model="settingsForm.author"
                    placeholder="请输入作者"
                  ></el-input>
                </el-form-item>
                <el-form-item label="表名前缀" prop="tablePrefix">
                  <el-input
                    v-model="settingsForm.tablePrefix"
                    style="display: inline-block;"
                    placeholder="填写前缀生成的文件将移除前缀（可多选），例如：plume_,user_"
                  ></el-input>
                </el-form-item>
                <el-form-item label="字段前缀" prop="columnPrefix">
                  <el-input
                    v-model="settingsForm.columnPrefix"
                    placeholder="填写前缀生成的文件将移除前缀（可多选），例如：n_,s_,d_"
                  ></el-input>
                </el-form-item>
              </div>
            </el-card>
          </el-form>
        </div>
      </el-col>
    </el-row>

    <!-- 页脚 -->
    <template slot="footer">
      <el-row>
        <el-col :span="4" :offset="20">
          <el-button
            :loading="loading"
            type="primary"
            @click="submitForm('settingsForm')"
            >一键下载</el-button
          >
          <el-button
            :loading="loading"
            type="primary"
            @click="submitForm('settingsForm', true)"
            >代码预览</el-button
          >
        </el-col>
      </el-row>
    </template>
    <show-content ref="showContent" />
  </d2-container>
</template>

<script>
import api from "@api";
import showContent from "./showContent";

export default {
  name: "generator",
  components: { showContent },
  data() {
    return {
      projectList: [],
      projectId: null,
      // 表
      searchValue: "",
      surfaceList: [],
      copySurfaceList: [],
      checkAll: false,
      checkedSurface: [],
      isIndeterminate: true,
      // 模板
      searchValueTemplate: "",
      templateList: [],
      copyTemplateList: [],
      checkAllTemplate: false,
      checkedTemplate: [],
      isIndeterminateTemplate: true,
      // 配置参数
      settingsForm: {
        packageName: "",
        author: "",
        tablePrefix: "",
        columnPrefix: ""
      },
      rules: {
        projectName: [
          {
            required: true,
            message: "请输入项目名称",
            trigger: "blur"
          },
          {
            min: 2,
            max: 50,
            message: "长度在 2 到 50 个字符",
            trigger: "blur"
          }
        ],
        basePackageName: [
          {
            required: true,
            message: "请输入基础包名",
            trigger: "blur"
          }
        ]
      },
      loading: false,
      apiurl: process.env.VUE_APP_API,
      open: "0"
    };
  },
  mounted() {
    getProjectList(this);
  },
  methods: {
    // 根据项目名称获取表
    handleSelectDatabase(value) {
      if (value) {
        this.projectId = value;
        getSurfaceListByPro(this, value);
        getTemplateListByPro(this, value);
        this.projectList?.forEach(item => {
          if (item.id === value) {
            this.settingsForm = { ...item, author: "code" };
          }
        });
      } else {
        this.projectId = null;
        this.surfaceList = [];
        this.copySurfaceList = [];
        this.templateList = [];
        this.copyTemplateList = [];
        this.checkedSurface = [];
        this.checkedTemplate = [];
      }
      this.searchValue = "";
      this.searchValueTemplate = "";
    },

    // 表列表筛选
    searchSurfaceList(val) {
      if (!val) {
        this.surfaceList = this.copySurfaceList;
      }
      let tempList = this.surfaceList;
      this.surfaceList = tempList.filter(item => item.indexOf(val) > -1);
    },

    // 表 全选
    handleCheckAllChange(val) {
      this.checkedSurface = val ? this.surfaceList : [];
      this.isIndeterminate = false;
    },

    // 表 checkbox 选择
    handleCheckedChange(value) {
      const checkedCount = value.length;
      this.checkAll = checkedCount === this.surfaceList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.surfaceList.length;
    },

    // 模板列表筛选
    searchTemplateList(val) {
      if (!val) {
        this.templateList = this.copyTemplateList;
      }
      let tempList = this.templateList;
      this.templateList = tempList.filter(item => item.name.indexOf(val) > -1);
    },

    // 模板全选
    handleCheckAllChangeTemplate(val) {
      this.checkedTemplate = val ? this.templateList.map(item => item.id) : [];
      this.isIndeterminateTemplate = false;
    },

    // 模板 checkbox 选择
    handleCheckedChangeTemplate(value) {
      const checkedCount = value.length;
      this.checkAllTemplate = checkedCount === this.templateList.length;
      this.isIndeterminateTemplate =
        checkedCount > 0 && checkedCount < this.templateList.length;
    },

    // 提交表单
    submitForm(formName, showCode = false) {
      if (this.checkedSurface.length === 0) {
        this.$message.warning("请选择要生成的表");
        return;
      }
      if (this.checkedTemplate.length === 0) {
        this.$message.warning("请选择要生成的模板");
        return;
      }
      this.$refs[formName].validate(valid => {
        if (valid) {
          let data = {
            projectId: this.projectId,
            tableNames: this.checkedSurface,
            templateIds: this.checkedTemplate,
            deploy:this.settingsForm
          };
          this.loading = true;
          submitGenerate(this, data, showCode);
          this.loading = false;
        }
      });
    }
  }
};

// 项目名称下拉
async function getProjectList(that) {
  let res = await api.templateProjectList();
  that.projectList = res;
}

// 表列表
async function getSurfaceListByPro(that, data) {
  let res = await api.listTableName(data);
  that.surfaceList = res || [];
  that.copySurfaceList = res || [];
}

// 模板列表
async function getTemplateListByPro(that, data) {
  let res = await api.templateListByPro(data);
  that.templateList = res || [];
  that.copyTemplateList = res || [];
  that.checkedTemplate = that.templateList.map(item => item.id);
  that.isIndeterminateTemplate = false;
  that.checkAllTemplate = true;
}

// 提交
async function submitGenerate(that, data, showCode) {
  let res = await api.generateSubmit(data);
  showCode
    ? that.$refs.showContent.show(res?.batchNo)
    : window.open(`${that.apiurl}generator/download?batchNo=${res?.batchNo}`);
    // : window.open(`${that.apiurl}downloads/${res?.batchNo}.zip`);
}
</script>

<style lang="scss">
.generator-left-select {
  width: 100%;
}

.generator-left-surface {
  height: calc(100vh - 350px);
  overflow: auto;
}

.generator-left-search {
  margin: 10px 0;
}

.generator-left-all-check {
  margin-bottom: 15px;
}

.generator-rigth-setting {
  height: calc(100vh - 200px);
  overflow: auto;
}

// .generator-rigth-setting .el-card__header {
//   padding: 16px 20px;
// }

// .generator-rigth-setting .el-form-item {
//   margin-bottom: 18px;
// }

.box-card {
  margin-bottom: 15px;
}

.el-checkbox {
  width: 120px;
}
</style>
